<template>
  <div class="resource-management">
    <el-card>
      <Load v-if="classifyLoad" />
      <div class="classifyMain" v-else>
        <div class="type">
          <div class="type-title">资源类型</div>
          <div class="type-container">
            <span
              :class="[resourceTypeIndex == index ? 'active' : '']"
              v-for="(type, index) in resourceType"
              :key="type.id"
              @click="handleType(index, type)"
            >
              {{ type.type }}
            </span>
          </div>
        </div>
        <div class="category">
          <div class="category-title">资源分类</div>
          <div class="category-container">
            <span
              :class="[resourceCategoryIndex == index ? 'active' : '']"
              v-for="(category, index) in resourceCategory"
              :key="category.id"
              @click="handleCategory(index, category)"
            >
              {{ category.category }}
            </span>
          </div>
        </div>
      </div>
    </el-card>
    <el-card style="margin-top: 20px">
      <Load v-if="tableLoad" />
      <div class="tableMain" v-else>
        <el-row>
          <el-col :span="6">
            <el-input
              v-model="queryParams.resourceName"
              placeholder="请输入资源名称"
            >
              <template #append>
                <el-icon style="cursor: pointer" @click="search">
                  <Search />
                </el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="18" style="display: flex; justify-content: end">
            <el-button type="primary" icon="plus" plain @click="add"
              >新建</el-button
            >
            <el-button type="warning" icon="refresh" plain @click="refresh"
              >重置</el-button
            >
            <el-button type="danger" icon="delete" plain>删除</el-button>
          </el-col>
        </el-row>

        <!-- 表格 -->

        <el-table :data="tableData" style="margin-top: 20px" stripe>
          <el-table-column type="index" width="55" label="#" />
          <el-table-column
            prop="resourceName"
            label="资源名称"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="resourceVersion"
            label="资源版本"
            align="center"
          ></el-table-column>
          <el-table-column prop="" label="资源图标" align="center">
            <template #default="prop">
              <el-image
                :src="prop.row.resourceImage"
                style="width: 50px; height: 50px"
                fit="contain"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="resourceCount" label="下载次数" align="center">
          </el-table-column>
          <el-table-column prop="" label="状态" align="center">
            <template #default="prop">
              <el-tag v-if="prop.row.resourceStatus" size="mini" type="success">
                启用
              </el-tag>
              <el-tag v-else size="mini" type="error"> 禁用 </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="" label="推荐" align="center">
            <template #default="prop">
              <el-tag v-if="prop.row.isRecommend" size="mini" type="primary">
                推荐
              </el-tag>
              <el-tag v-else size="mini" type="info"> 默认 </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="resourceCount" label="说明文档" align="center">
            <template #default="prop">
              <el-tag
                type="danger"
                style="cursor: pointer"
                v-if="prop.row.docStatus == 0"
              >
                未上传
              </el-tag>
              <el-tag type="warning" v-if="prop.row.docStatus == 1">
                审核中
              </el-tag>
              <el-tag type="info" v-if="prop.row.docStatus == 2">
                已上传
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="" label="操作" align="center" width="300">
            <template #default="prop">
              <el-button
                type="primary"
                icon="edit"
                @click="update(prop.row.id)"
                size="small"
              >
                编辑
              </el-button>
              <el-button type="danger" icon="delete" size="small">
                删除
              </el-button>
              <el-button
                type="warning"
                icon="UploadFilled"
                v-if="prop.row.docStatus == 0"
                @click="toUploadDoc(prop.row)"
                size="small"
              >
                上传文档
              </el-button>
              <el-button
                icon="Promotion"
                v-else
                @click="toUploadDoc(prop.row)"
                type="success"
                size="small"
              >
                编辑文档
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div
          class="pagination"
          style="margin-top: 20px; display: flex; justify-content: center"
        >
          <el-pagination
            background
            layout="total, prev, pager, next, jumper"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pageSize"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 新增资源弹出框 -->
    <el-dialog
      v-model="resourceDialogVisible"
      :title="dialogTitle"
      width="700"
      @close="handleDialogClose"
    >
      <el-form
        :model="dialogFormData"
        :rules="rules"
        ref="ruleFormRef"
        status-icon
      >
        <el-form-item label="资源名称:" prop="resourceName">
          <el-input
            v-model="dialogFormData.resourceName"
            placeholder="请输入资源名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="资源描述:" prop="resourceDesc">
          <el-input
            v-model="dialogFormData.resourceDesc"
            placeholder="请输入资源描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="资源类型:" prop="typeId">
          <el-select
            v-model="dialogFormData.typeId"
            placeholder="请选择资源类型"
            @change="handleSelectChange"
          >
            <el-option
              v-for="item in resourceType"
              :key="item.id"
              :label="item.type"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资源分类:" prop="categoryId">
          <el-select
            v-model="dialogFormData.categoryId"
            placeholder="请选择资源分类"
          >
            <el-option
              v-for="item in resourceCategory"
              :key="item.id"
              :label="item.category"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资源版本:" prop="resourceVersion">
          <el-input
            v-model="dialogFormData.resourceVersion"
            placeholder="请输入资源版本"
          ></el-input>
        </el-form-item>
        <el-form-item label="图片地址:" prop="resourceImage">
          <el-input
            v-model="dialogFormData.resourceImage"
            placeholder="请输入图片地址:"
          ></el-input>
        </el-form-item>
        <el-form-item label="官方网址:" prop="resourceUrl">
          <el-input
            v-model="dialogFormData.resourceUrl"
            placeholder="请输入官方网址"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="是否启用:"
          label-width="80"
          v-if="permissionCheck(['resource:update'])"
        >
          <el-switch
            v-model="dialogFormData.resourceStatus"
            inline-prompt
            active-icon="Check"
            inactive-icon="Close"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item
          label="是否推荐:"
          label-width="80"
          v-if="permissionCheck(['resource:update'])"
        >
          <el-switch
            v-model="dialogFormData.isRecommend"
            inline-prompt
            active-icon="Check"
            inactive-icon="Close"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel" type="text">Cancel</el-button>
          <el-button type="primary" @click="submit(ruleFormRef)">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  reqResourceType,
  reqResourceCategory,
  reqUpdateResourceInfo,
  reqAddResourceInfo,
  queryById,
  reqQueryPage,
} from "@/api/resource";
import { onMounted } from "vue";
import { ref } from "vue";
import Load from "@/components/Load.vue";
import { ElMessage } from "element-plus";
import permissionCheck from "@/utils/permissionCheck";
import { useRouter } from "vue-router";

const $router = useRouter();

const total = ref(0);

// 类型的加载动画
const classifyLoad = ref(true);
// 资源信息的加载动画
const tableLoad = ref(true);

// 资源类型下标
const resourceTypeIndex = ref(0);
// 资源类型Id
const resourceTypeId = ref();
// 资源分类Id --- 如果有值，那么说明用户点了资源分类，此时用户在新增资源时，新增成功则再该分类下获取最新数据，不要回跳到类型查询
const resourceCategoryId = ref();

// 资源分类下标
const resourceCategoryIndex = ref();

// 资源类型数据
const resourceType = ref([]);

// 资源分类数据
const resourceCategory = ref([]);

// 表格数据
const tableData = ref([]);

// 以下为弹出层数据
const ruleFormRef = ref();

// 控制弹出层是否隐藏
const resourceDialogVisible = ref(false);

// 弹出层标题
const dialogTitle = ref("");

// 弹出层的数据
const dialogFormData = ref({
  resourceName: "",
  typeId: "",
  categoryId: "",
  resourceDesc: "",
  resourceVersion: "",
  resourceImage: "",
  resourceUrl: "",
  resourceStatus: "",
  isRecommend: "",
});

// 查询参数
const queryParams = ref({
  page: 1,
  pageSize: 5,
  typeId: "",
  categoryId: "",
  resourceName: "",
});

// 表单校验规则
const rules = ref({
  resourceName: [
    { required: true, message: "请输入资源名称", trigger: "blur" },
  ],
  resourceDesc: [
    { required: true, message: "请输入资源描述", trigger: "blur" },
    { min: 0, max: 200, message: "长度为0至200", trigger: "blur" },
  ],
  typeId: [{ required: true, message: "请选择资源类型", trigger: "change" }],
  categoryId: [
    { required: true, message: "请选择资源分类", trigger: "change" },
  ],
  resourceVersion: [
    { required: true, message: "请输入资源版本", trigger: "blur" },
  ],
  resourceImage: [{ required: true, message: "请上传图片", trigger: "blur" }],
  resourceUrl: [{ required: true, message: "请上传官方网址", trigger: "blur" }],
});

// ----------- 弹出层数据结束

onMounted(() => {
  getResourceType();
});

// 获取资源类型
const getResourceType = () => {
  reqResourceType().then((res) => {
    if (res.code == 200) {
      resourceType.value = res.data;
      getResourceCategory(resourceType.value[0].id);
      resourceTypeId.value = resourceType.value[0].id;
      queryParams.value.typeId = resourceTypeId.value;
      queryPage();
    }
  });
};

// 获取资源分类
const getResourceCategory = (typeId) => {
  reqResourceCategory(typeId).then((res) => {
    if (res.code == 200) {
      resourceCategory.value = res.data;
      classifyLoad.value = false;
    }
  });
};

// 搜索资源信息 根据类型
const queryPage = () => {
  reqQueryPage(queryParams.value).then((res) => {
    if (res.code == 200) {
      tableData.value = res.data.result;
      total.value = res.data.total;
      tableLoad.value = false;
    }
  });
};

// 点击资源类型的回调  收集资源类型的id
const handleType = (index, type) => {
  resourceTypeIndex.value = index;
  resourceTypeId.value = type.id;
  resourceCategoryIndex.value = -1; // 点击大类时，子分类不需要高亮，默认查大类下资源信息
  getResourceCategory(type.id);
  queryParams.value.typeId = type.id;
  queryParams.value.categoryId = "";
  queryParams.value.page = 1;
  queryPage();
};

// 点击资源分类的回调  收集资源分类的id
const handleCategory = (index, category) => {
  total.value = 0;
  resourceCategoryIndex.value = index;
  resourceCategoryId.value = category.id;
  queryParams.value.page = 1;
  queryParams.value.categoryId = category.id;
  queryPage();
};

// 查询
const search = () => {
  if (queryParams.value.resourceName) {
    initResource();
  }
};

// 重置参数
const refresh = () => {
  queryParams.value.page = 1;
  queryParams.value.resourceName = "";
  total.value = 0;
  initResource();
};

// 打开新增弹出层
const add = () => {
  dialogTitle.value = "新增资源";
  resourceDialogVisible.value = true;
};

// 提交新增或修改资源数据
const submit = () => {
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {

      // 上传文件

      if (dialogFormData.value.id) {
        // 此处为修改资源数据
        reqUpdateResourceInfo(dialogFormData.value).then((res) => {
          if (res.code == 200) {
            ElMessage.success("修改成功");
            initResource();
          } else {
            ElMessage.error("修改失败，请重试");
          }
        });
      } else {
        // 此处为新增数据
        reqAddResourceInfo(dialogFormData.value).then((res) => {
          if (res.code == 200) {
            ElMessage.success("提交成功");
            initResource();
          } else {
            ElMessage.error("提交失败，请重试");
          }
        });
        clearDialogFormData();
      }

      resourceDialogVisible.value = false;
    }
  });
};

// 重新加载资源信息
const initResource = () => {
  /**
   * 提交成功后，根据用户当前所在的页面获取最新资源信息
   *
   */
  if (queryParams.value.categoryId) {
    // 用户已经点击过分类
    queryParams.value.typeId = "";
    queryParams.value.categoryId = resourceCategoryId.value;
  } else {
    // 用户没有点击过分类
    queryParams.value.typeId = resourceTypeId.value;
  }
  queryPage();
};

// 编辑数据
const update = (id) => {
  dialogTitle.value = "编辑资源";
  dialogFormData.value.id = id;
  queryById(id).then((res) => {
    if (res.code == 200) {
      dialogFormData.value = res.data;
      getResourceCategory(dialogFormData.value.typeId);
    }
  });
  resourceDialogVisible.value = true;
};

// 弹出层取消按钮  清空表单数据
const cancel = () => {
  ruleFormRef.value.resetFields();
  resourceDialogVisible.value = false;
  clearDialogFormData();
};

// 关闭弹出层的回调
const handleDialogClose = () => {
  clearDialogFormData();
  ruleFormRef.value.resetFields();
};

// 重置弹出框的表单数据
const clearDialogFormData = () => {
  dialogFormData.value = {
    resourceName: "",
    typeId: "",
    categoryId: "",
    resourceDesc: "",
    resourceVersion: "",
    resourceImage: "",
    resourceUrl: "",
    // resourceStatus: "",
    // isRecommend: "",
  };
};

// 页数发生变化时触发
const handleCurrentChange = (newPage) => {
  queryParams.value.page = newPage;
  initResource();
};

// 上传/修改资源文档
const toUploadDoc = (data) => {
  $router.push({
    query: {
      resourceId: data.id,
      status: data.docStatus,
    },
    path: "/upload-resource-doc",
  });
};
</script>

<style scoped lang="scss">
.resource-management {
  width: 100%;
  height: calc(100vh - 95px);
  box-sizing: border-box;
}
.type,
.category {
  width: 100%;
  display: flex;
  align-items: center;
  margin: 0 0 20px 0;

  .type-title,
  .category-title {
    font-weight: bolder;
    margin-right: 25px;
  }
  .type-container,
  .category-container {
    display: flex;
    span {
      display: inline-block;
      padding: 5px 20px;
      box-sizing: border-box;
      border-radius: 30px;
      background-color: rgba(167, 197, 246, 0.231);
      margin-right: 10px;
      font-size: 14px;
      cursor: pointer;
    }
    span.active {
      border: 1px solid rgb(40, 96, 249);
      background-color: #fff;
      color: rgb(40, 96, 249);
    }
  }
}
</style>